﻿using ApiData.JsonDB;
using Newtonsoft.Json.Linq;
using SqlSugar;

namespace ApiData.Logic
{
    public class Randomx
    {
        public static Common.ResultData Execute(Model.tables tab, string value)
        {
            var path = tab.jsondata;
            var phy = Directory.GetCurrentDirectory();
            var real = phy + path;
            var cols = tab.structure.Split("\r\n", StringSplitOptions.RemoveEmptyEntries);

            List<Model.Dto.Structure> st = new List<Model.Dto.Structure>();
            foreach (var item in cols)
            {
                if (item.IsNullOrWhiteSpace()) continue;
                var col = item.Split('-');
                st.Add(new Model.Dto.Structure()
                {
                    name = col[0],
                    type = col[1],
                    defaultvalue = col[2],
                    des = col[3]
                });
            }
            var db = new InitDB(real);
            object data = null;
            int count = db.Count(), number = value.ToInt();
            if (count < number)
            {
                data = db.Select();
            }
            else
            {
                var list = new List<object>();
                while (list.Count < number)
                {
                    Random ran = new Random(DateTime.Now.Millisecond);
                    int idx = ran.Next(0, count);
                    var temp = db.GetOfIndex(idx);
                    if (!list.Any(x => x == temp))
                    {
                        list.Add(temp);
                    }
                }
                data = list;
                count = number;
            }

            if (data == null)
                return new Common.ResultData().Fail("找不到相关信息");
            else
                return new Common.ResultData().SuccessData(count, data);
        }

        public static Common.ResultData Structure(Model.tables tab)
        {
            var cols = tab.structure.Split("\r\n", StringSplitOptions.RemoveEmptyEntries);

            List<Model.Dto.Structure> st = new List<Model.Dto.Structure>();
            foreach (var item in cols)
            {
                if (item.IsNullOrWhiteSpace()) continue;
                var col = item.Split('-');
                st.Add(new Model.Dto.Structure()
                {
                    name = col[0],
                    type = col[1],
                    defaultvalue = col[2],
                    des = col[3]
                });
            }

            return new Common.ResultData().SuccessData(st.Count, st);
        }
    }
}